package com.waverider.promotion.web.bg.screen;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;

import com.iacrqq.util.StringUtil;
import com.waverider.promotion.biz.manager.ItemManager;
import com.waverider.promotion.domain.PromotionDO;
import com.waverider.promotion.model.BaseQueryModel;
import com.waverider.promotion.model.PromotionQueryModel;
import com.waverider.promotion.model.ResultModel;
import com.waverider.promotion.web.AbstractLoginedController;

public class PromotionList extends AbstractLoginedController
{

	private static final Log logger = LogFactory.getLog(PromotionList.class);
	
	private ItemManager itemManager;

	@Override
	protected ModelAndView handleLogined(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		HttpSession session = request.getSession();
		Long currentPage = null;
		Date startTime = null;
		Date endTime = null;
		Integer status = null;
		String strCurrentPage = request.getParameter("current_page");
		String strStartTime = request.getParameter("start_time");
		String strEndTime = request.getParameter("end_time");
		String strStatus = request.getParameter("status");
		if (StringUtil.isBlank(strCurrentPage))
		{
 			currentPage = 1L;
		}
		else
		{
			try
			{
				currentPage = Long.valueOf(strCurrentPage);
			}
			catch (NumberFormatException e)
			{
				logger.error(e);
				currentPage = 1L;
			}
		}
		
		SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT_1);
		
		if (!StringUtil.isBlank(strStartTime))
		{
			try
			{
				startTime = format.parse(strStartTime);
			}
			catch (ParseException e)
			{
				logger.error(e);
				startTime = null;
			}
		}
		
		if (!StringUtil.isBlank(strEndTime))
		{
			try
			{
				endTime = format.parse(strEndTime);
			}
			catch (ParseException e)
			{
				logger.error(e);
				endTime = null;
			}
		}
		
		if (!StringUtil.isBlank(strStatus))
		{
			try
			{
				status = Integer.valueOf(strStatus);
			}
			catch (NumberFormatException e)
			{
				logger.error(e);
				status = null;
			}
		}
		
		PromotionQueryModel queryModel = PromotionQueryModel.buildQueryModel(getShopId(session), status, startTime, endTime, currentPage, BaseQueryModel.DEFAULT_PAGE_SIZE);
		ResultModel<PromotionDO> resultModel = itemManager.getPromotionList(queryModel);

		ModelAndView mv = new ModelAndView("bg/promotionList");
		Map<String, Object> context = mv.getModel();
		context.put("resultModel", resultModel);
		context.put("pageNo", 2);
		return mv;
	}

	public void setItemManager(ItemManager itemManager)
	{
		this.itemManager = itemManager;
	}
}
